﻿
using System;
using System.Collections.Generic;
using System.Linq;
using sharpxbot.Core.Messaging;
using sharpxbot.Core.Threading;
using sharpxbot.Plugins.Base;
using sharpxbot.Plugins.Loaders;
using sharpxbot.Plugins.Registry;
namespace sharpxbot.Plugins
{
    public class PluginManager : IActive, IPluginManager, IProcessor
    {
        public PluginManager(IPluginLoader pluginLoader, string pluginsPath)
        {
            this.pluginLoader = pluginLoader;
            this.pluginsPath = pluginsPath;

            pluginsRegistry = new List<PluginInfo>(10);

            InitPlugins();
        }

        #region IActive Members

        public bool IsRunning { get; private set; }

        public void Start()
        {
            foreach (IPlugin p in pluginsRegistry)
            {
                ActiveHelper.StartIfActive(p);
            }

            IsRunning = true;
        }

        public void Stop()
        {
            foreach (IPlugin p in pluginsRegistry)
            {
                ActiveHelper.StopIfActive(p);
            }

            IsRunning = false;
        }

        #endregion

        #region IProcessor Members

        public void ProcessMessage(XmppMessage message)
        {
            foreach (PluginInfo p in pluginsRegistry)
            {
                if (p.IsEnabled)
                {
                    p.Plugin.ProcessMessage(message);
                }
            }
        }

        #endregion

        #region IPluginManager Members

        public PluginInfo GetPluginInfo(Guid pluginID)
        {
            return pluginsRegistry.
                Where(p => p.Plugin != null && p.Plugin.GUID == pluginID).FirstOrDefault();
        }

        #endregion

        private void InitPlugins()
        {
            if (pluginLoader != null)
            {
                var loadedPlugins = pluginLoader.LoadPlugins(pluginsPath);

                foreach (IPlugin p in loadedPlugins)
                {
                    PluginInfo info = new PluginInfo()
                    {
                        Plugin = p,
                        IsEnabled = true,
                        EnableDate = DateTime.Now
                    };

                    pluginsRegistry.Add(info);
                }
            }
        }

        #region Private fields

        private IPluginLoader pluginLoader;
        private string pluginsPath;

        private ICollection<PluginInfo> pluginsRegistry;

        #endregion
    }
}
